using Godot;
using Ink.Parsed;
using System;
using System.IO;

class CatpurePicManager
{
    public static CatpurePicManager _instance = null;

    private const string shotPath = "user://SaveScreenShot";

    private const string ShotSuffix = ".png";
    public static CatpurePicManager getInstance()
    {
        if (_instance == null)
        {
            _instance = new CatpurePicManager();
        }
        return _instance;
    }

    public void SaveCaptureScreenShot(string filename = null)
    {
        Node main = GameUtil.GetGameRoot();

        ViewportTexture texture = main.GetViewport().GetTexture();

        //完成截图事件
        EventManager.getInstance().dispatchEvent(EventType.EVENT_CATCH_SHOT_FINISH);


        Image image = texture.GetImage();

        string time = TimeUtil.GetNowTImeString();

        string name = filename != null ? filename : time;

        if (!DirAccess.DirExistsAbsolute(shotPath))
        {
            _ = DirAccess.MakeDirAbsolute(shotPath);  //没有目录则创建目录
        }

        //Directory.CreateDirectory(shotPath);
        var err = image.SavePng(shotPath + "/" + name + ShotSuffix);
        GD.Print(err);
        //ImageTexture texture = GetViewport().GetTexture() as ImageTexture;
    }

    public ImageTexture GetImageFromShotPath(string name)
    {
        //ImageTexture texture = new ImageTexture();
        Image image = new Image();
        var err = image.Load(shotPath + "/" + name + ShotSuffix);
        GD.Print(err);
        return ImageTexture.CreateFromImage(image);
    }

    public void DeletePngFromName(string filename)
    {
        if (Godot.FileAccess.FileExists(shotPath + "/" + filename + ShotSuffix))
        {
            Godot.DirAccess.RemoveAbsolute(shotPath + "/" + filename + ShotSuffix);
        }
    }

    public void ClearAllPng()
    {
        Godot.DirAccess.RemoveAbsolute(shotPath);
    }
}